package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.User;
import net.sf.json.JSONObject;

/**
 * @author bing.zhang06@hand-china.com 2021/7/24 16:56
 **/
@WebServlet(urlPatterns = {"/a", "/b"})
public class ServletA extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        if ("/a".equals(requestURI)) {
            doA(req, resp);
        } else if ("/b".equals(requestURI)) {
            doB(req, resp);
        }
    }

    private void doB(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.接收参数
        String uuid = req.getParameter("uuid");
        int userid = Integer.parseInt(uuid);
        User user = null;
        switch (userid) {
            case 1:
                user = new User("1", "张三", "abc", 17);
                break;
            case 2:
                user = new User("2", "张三2", "abc2", 18);
                break;
            case 3:
                user = new User("3", "张三3", "abc3", 19);
                break;
            case 4:
                user = new User("4", "张三4", "abc4", 20);
                break;
            default:
                user = new User();
        }

        //java->json
        JSONObject jsonObject = JSONObject.fromObject(user);//json

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print(jsonObject);
    }

    private void doA(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        if ("admin".equals(name)) {
            writer.println("账户已被注册");
        } else {
            writer.println("账户可用");
        }
    }
}
